package com.weixing.mall.provider.support.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.provider.model.vo.GoodsIdentificationVo;
import com.weixing.mall.util.SKUUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 检货管理订单导出
 */
public class GoodsIdentificationExcalDownLoad {
    private static final Logger logger = LoggerFactory.getLogger(GoodsIdentificationExcalDownLoad.class);

    public static void ExcalDownload(List<GoodsIdentificationVo> list, String filedNames, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            //String fileName = URLEncoder.encode("检货管理订单列表", "UTF-8");
            String fileName = "检货管理订单列表"+ DateUtil.now();
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //指定导出字段
            if (StrUtil.isNotEmpty(filedNames)) {
                String[] filedNamesArray = filedNames.split(",");
                EasyExcel.write(response.getOutputStream(), GoodsIdentificationExcalData.class).includeColumnFiledNames(loadFiledNames(filedNamesArray)).sheet("sheet1").doWrite(loadDataAndUrl(list));
            } else {// 不指定默认全部
                EasyExcel.write(response.getOutputStream(), GoodsIdentificationExcalData.class).sheet("sheet1").doWrite(loadDataAndUrl(list));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getCause() instanceof ExcelDataConvertException) {
                ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) e.getCause();
                String cellMsg = "";
                CellData cellData = excelDataConvertException.getCellData();
                //这里有一个celldatatype的枚举值,用来判断CellData的数据类型
                CellDataTypeEnum type = cellData.getType();
                if (type.equals(CellDataTypeEnum.NUMBER)) {
                    cellMsg = cellData.getNumberValue().toString();
                } else if (type.equals(CellDataTypeEnum.STRING)) {
                    cellMsg = cellData.getStringValue();
                } else if (type.equals(CellDataTypeEnum.BOOLEAN)) {
                    cellMsg = cellData.getBooleanValue().toString();
                }
                String errorMsg = String.format("excel表格:第%s行,第%s列,数据值为:%s,该数据值不符合要求,请检验后重新导入!<span style=\"color:red\">请检查其他的记录是否有同类型的错误!</span>", excelDataConvertException.getRowIndex() + 1, excelDataConvertException.getColumnIndex(), cellMsg);
                logger.error(errorMsg);
            }
        }
    }

    /**
     * 封装数据并将url替换为全路径、订单来源转换
     * @param list
     * @return
     */
    private static List<GoodsIdentificationExcalData> loadDataAndUrl(List<GoodsIdentificationVo> list) throws Exception {
        List<GoodsIdentificationExcalData> listData = Lists.newArrayList();
        for (GoodsIdentificationVo g : list) {
            GoodsIdentificationExcalData gd = new GoodsIdentificationExcalData();
            BeanUtils.copyProperties(g, gd);
            if(ObjectUtil.isNotEmpty(g.getProductImg())){
                gd.setProductImg(new URL(GlobalConstant.IMG_PATH_URL + g.getProductImg()+GlobalConstant.IMG_PATH_URL_SUFFIX));
            }
            if (g.getOrderForm() != null) {
                gd.setOrderForm(g.getOrderForm().getDesp());
            }
            if (g.getOrderType() != null) {
                gd.setOrderType(g.getOrderType().getDesp());
            }
            if (g.getOrderMateRule() != null) {
                gd.setOrderMateRule(g.getOrderMateRule().getDesp());
            }
            if(ObjectUtil.isNotEmpty(g.getProductSkuDesp())){
                gd.setColor(SKUUtils.color2(g.getProductSkuDesp()));
                gd.setSize(SKUUtils.size2(g.getProductSkuDesp()));
            }
            if (g.getAfterSaleTag() != null && g.getAfterSaleTag() == 1 ) {
                gd.setAfterSaleTag("是");
            }else{
                gd.setAfterSaleTag("否");
            }
            listData.add(gd);
        }
        return listData;
    }

    /**
     * 封装指定字段
     *
     * @param filedNamesArray
     * @return
     */
    private static Set<String> loadFiledNames(String[] filedNamesArray) {
        Set<String> excludeColumnFiledNames = new HashSet<String>();
        for (int i = 0; i < filedNamesArray.length; i++) {
            excludeColumnFiledNames.add(filedNamesArray[i]);
        }
        return excludeColumnFiledNames;
    }
}
